package com.ssyan.singleton.type2;

/**
 * @author ssyan
 * @Description 饿汉式2
 * @create 2021/8/27 17:42
 * @Version 1.0
 */
public class SingletonTest02 {
    public static void main(String[] args) {
        //测试
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance == instance2);//true
        System.out.println(instance.hashCode());
        System.out.println(instance2.hashCode());
    }
}

//饿汉式（静态常量）
class Singleton {

    //1.构造器私有化，外部能new
    private Singleton() {
    }

    //2.本类内部创建声明对象实例
    private static Singleton instance;

    static { //在静态代码块中，创建单例对象
        instance = new Singleton();
    }

    //3.提供一个公用的静态方法，返回实例对象
    public static Singleton getInstance() {
        return instance;
    }
}
